﻿using AutoMapper;
using Gengens.Disk.Entity.model.user;
using Gengens.Disk.Service.service;
using Gengens.Disk.WebApi.dto;
using Gengens.Disk.WebApi.dto.input.user;
using Gengens.Disk.WebApi.dto.output;
using Gengens.Disk.WebApi.util;
using Microsoft.AspNetCore.Mvc;

namespace Gengens.Disk.WebApi.Controllers.user
{
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly UserService _userService;
        private readonly ILogger _logger;
        private readonly IMapper _mapper;

        public UsersController(UserService userService, ILogger<UsersController> logger, IMapper mapper)
        {
            _userService = userService;
            _logger = logger;
            _mapper = mapper;
        }

        [HttpPost("register")]
        public async Task<ApiRet> Register([FromBody] UserForRegisterDto registerDto)
        {
            var userByName = await _userService.SelectAsync(u => u.Username == registerDto.Username);

            if (userByName != default && userByName.Count > 0)
            {
                return ApiRet.Fail("用户名已被占用", registerDto.Username);
            }

            UserInfo u = _mapper.Map<UserInfo>(registerDto);
            UserInfo newU = await _userService.InsertAsync(u);
            await _userService.SaveChanegsAsync();
            LoginInfo info = new LoginInfo();
            info.Username = newU.Username;
            info.Ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? string.Empty;
            info.UserId = newU.Id;
            info.Remark = "注册时生成";

            string token = LoginUtils.GetStringFromLoginfo(info);
            return ApiRet.Ok("注册成功", token);
        }

        [HttpPost("login")]
        public async Task<ApiRet> Login([FromBody] UserForLoginDto loginDto)
        {
            var uByDb = await _userService.SelectAsync(u => (
                u.Email == loginDto.Username ||
                u.Phone == loginDto.Username ||
                u.Username == loginDto.Username)
                && u.Password == loginDto.Password);

            if (!ListUitls.HasValue(uByDb))
                return ApiRet.Fail("用户名或密码输入错误");

            var user = uByDb.First();

            LoginInfo info = new LoginInfo();
            info.Username = user.Username;
            info.Ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? string.Empty;
            info.UserId = user.Id;
            info.Remark = "登录时生成";

            string token = LoginUtils.GetStringFromLoginfo(info);
            return ApiRet.Ok("登录成功", token);
        }
    }
}
